package com.cqut.forum.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cqut.forum.entity.Messages;
import com.cqut.forum.entity.User;
import com.cqut.forum.service.MessageService;

@Controller
public class MessageAction {
	@Resource
	private MessageService messageService;
	@RequestMapping("/meesage/get_message")
	@ResponseBody
	public List<Map<String, Object>> getMessages(HttpServletRequest request,int index,int size){
		User user = (User)request.getSession().getAttribute("user");
		List<Map<String, Object>> messages = messageService.getMessages(user.getUserId(),index,size);
		
		messageService.haveReadMyMessages(user.getUserId(),"留言");
		return messages;
	}
	
	@SuppressWarnings("deprecation")
	@RequestMapping("/messages/message_reply")
	@ResponseBody
	public Map<String, Object> addMessageReply(HttpServletRequest request,int messageId,
			String replyContent){
		User user = (User)request.getSession().getAttribute("user");
		Map<String, Object> result = new HashMap<String, Object>();
		Messages message = messageService.getMessageById(messageId);
		
		Messages reply = new Messages();
		reply.setAboveMessagesId(messageId);
		reply.setAcceptUserId(message.getAcceptUserId());
		reply.setMessagesContents(replyContent);
		reply.setMessagesState("未读");
		reply.setMessagesTime(new Date());
		reply.setLastReplyTime(reply.getMessagesTime());
		reply.setUser(user);
		messageService.saveMessage(reply);
		
		//更新原博客评论和访问信息
		//message.setMessagesState("未读");
		message.setLastReplyTime(reply.getMessagesTime());
		messageService.updateMessage(message);
		
		//封装数据提供前台展示
		result.put("image", user.getUserPhoto());
		result.put("name", user.getUserName());
		result.put("content", reply.getMessagesContents());
		result.put("time", ((Date)reply.getMessagesTime()).toLocaleString());
		result.put("userId", user.getUserId());
		result.put("messageId", message.getMessagesId());
		return result;
		
	}
	
	@RequestMapping("/message/add_message")
	@ResponseBody
	public String addMessage(HttpServletRequest request,int userId,String contents){
		User user = (User)request.getSession().getAttribute("user");
		if(!"".equals(contents)&&contents!=null){
			Messages m = new Messages();
			m.setAboveMessagesId(-1);
			m.setAcceptUserId(userId);
			m.setMessagesContents(contents);
			m.setMessagesState("未读");
			m.setMessagesTime(new Date());
			m.setLastReplyTime(m.getMessagesTime());
			m.setUser(user);
			messageService.saveMessage(m);
		}
		return "留言成功";
	}
}
